package com.weiyuwqj.admin.controller.admin.sys;

import com.weiyuwqj.admin.controller.base.BaseController;
import com.weiyuwqj.api.service.SysContractsService;
import com.weiyuwqj.api.service.*;
import com.weiyuwqj.api.service.BasUserService;
import com.weiyuwqj.api.common.Paginator;
import com.weiyuwqj.api.constant.Constants;
import com.weiyuwqj.api.constant.Message;
import com.weiyuwqj.api.exception.CrowdException;
import com.weiyuwqj.api.model.*;
import com.weiyuwqj.api.model.vo.BasUserInfoVo;
import com.weiyuwqj.api.util.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhangyong on 2016/7/19.
 */
@Controller
public class SysUserController extends BaseController{

    @Resource
    SysUserService sysUserService;

    @Resource
    SysUserRoleService userRoleService;

    @Autowired
    SysTempcodeService tempcodeService;

    @Autowired
    SysNoticeTypeService noticeTypeService;

    @Autowired
    BasUserService userService;

    @Autowired
    SysContractsService contractsService;

    @Autowired
    SysAssetCompanyService sysAssetCompanyService;


    @ResponseBody
    @RequestMapping("/admin/doLogin")
       public Object login(String username,String password,HttpServletRequest request){
        SysUser user = sysUserService.doLogin(username, password);
        if(null==user){
            return Message.FAIL;
        }
        request.getSession().setAttribute("userId",user.getId());
        request.getSession().setAttribute("username",user.getSysUserName());
        request.getSession().setAttribute("userType",user.getType());
        Map map = new HashMap();
        map.put("username",user.getSysUserName());
        map.put("userType",user.getType());
        map.put("result","success");
        if(user.getType()==2){
            request.getSession().setAttribute("assetId",user.getAssetId());
        }
        return map;
    }

    /**
     * 浏览器版本过低，跳转error页面
     * @return
     */
    @RequestMapping("/admin/empLogin/error")
    public Object error(){
        return "error";
    }

    //退出登录
    @RequestMapping("/admin/loginOut")
    public Object loginOut(HttpSession session){
        session.invalidate();
        return "login";
    }

    //后台不分页列表接口
    @ResponseBody
    @RequestMapping("/admin/sysuser/noPageList")
    public Object noPageList(Integer type){
        Map map=new HashMap();
        map.put("type",type);
        return sysUserService.getList(map);
    }

    //后台列表接口
    @ResponseBody
    @RequestMapping("/admin/sysuser/list")
    public Object list(Paginator p,
                       String username,
                       String mobile,
                       String status,
                       String beginDateTime,
                       String endDateTime,
                       Integer type){
        Map map = new HashMap();
        if(StringUtils.isNotEmpty(username)){
            map.put("username", username);
        }
        if(StringUtils.isNotEmpty(mobile)){
            map.put("mobile", mobile);
        }
        if(StringUtils.isNotEmpty(status)){
            map.put("status", status);
        }
        if(StringUtils.isNotEmpty(beginDateTime)){
            map.put("beginDateTime", beginDateTime);
        }
        if(StringUtils.isNotEmpty(endDateTime)){
            map.put("endDateTime", endDateTime);
        }
        map.put("type", type);
        return sysUserService.getList(p,map);
    }

    @ResponseBody
    @RequestMapping("/admin/sysuser/getOne")
    public Object getOne(Integer id){
        SysUser user =sysUserService.selectByKey(id);
        user.setPassword("");
        Map map=new HashMap();
        map.put("userRole",userRoleService.getOneByUserId(id));
        map.put("user",user);
        return map;

    }

    @ResponseBody
    @RequestMapping("/admin/sysuser/getUserType")
    public Object getUserType(){
        Integer userId=(Integer)getSession().getAttribute("userId");
        SysUser sysUser= sysUserService.selectByKey(userId);
        Map map=new HashMap();
        map.put("userType",sysUser.getType());
        return map;

    }

    @ResponseBody
    @RequestMapping("/admin/sysuser/modify")
    public Object modify(SysUser user,Integer character){
        user.setPassword(null);
        sysUserService.updateNotNull(user);
        SysUserRole role = new SysUserRole();
        int userId = user.getId();
        SysUserRole userRole = userRoleService.getOneByUserId(userId);
        if (userRole != null) {
            userRole.setRoleId(character);
            userRoleService.updateNotNull(userRole);
        } else {
            role.setRoleId(character);
            role.setUserId(userId);
            userRoleService.save(role);
        }
        return Message.OK;
    }

    @ResponseBody
    @RequestMapping("/admin/sysuser/add")
    public Object add(SysUser user ,Integer character){
        SysUser sysUser=sysUserService.getOneByUsername(user.getSysUserName());
        if(sysUser!=null){
            throw new CrowdException("sys.user.add.user_exist");
        }
        user.setAddip(IpUtils.get());
        user.setAddtime(new Date());
        user.setStatus(1);
        String salt = RandomCodesUtils.createRandom(false, 4);
        user.setSalt(salt);
        try {
            user.setPassword(MD5.toMD5(user.getPassword()+salt));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        sysUserService.insertUser(user,character);
        return Message.OK;
    }

    @ResponseBody
    @RequestMapping("/admin/sysuser/modifyPassword")
    public Object modifyPassword(SysUser user){
        SysUser sysUser=sysUserService.selectByKey(user.getId());
        try {
            user.setPassword(MD5.toMD5(user.getPassword()+sysUser.getSalt()));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        sysUserService.updateNotNull(user);
        return Message.OK;
    }

    //获取前台未绑定用户
    @ResponseBody
    @RequestMapping("/admin/sysuser/listUser")
    public Object listSalesman(Integer type){
        Map map = new HashMap();
        if(type ==1){
            map.put("customerType", 2);
        }
        if(type ==3){
            map.put("customerType", 1);
        }
        return userService.listUser(map);
    }

    //资产方借款人列表
    @ResponseBody
    @RequestMapping("/admin/sysuser/getAssetList")
    public Object getAssetList(){
        Integer assetId=(Integer)getSession().getAttribute("assetId");
        return userService.getAssetList(assetId);
    }


//    //绑定业务员
//    @ResponseBody
//    @RequestMapping("/admin/sysuser/bindingUser")
//    public Object bindingUser(Integer sysUserId,Integer userId,String mobileCode){
//        BasUserInfoVo user =userService.getUserInfoById(userId);
//        if(user ==null){
//            Message.RESULT.put("result", "fail");
//            Message.RESULT.put("messageCode", "sysUser.modifyPass.user.notExist");
//            Message.RESULT.put("message", "不存在该手机用户");
//            return Message.RESULT;
//        }
//        if(user.getCustomerType() != 1){
//            Message.RESULT.put("result", "fail");
//            Message.RESULT.put("messageCode", "sysUser.has_bangding_user");
//            Message.RESULT.put("message", "改用户已被绑定");
//        }
//        String randomCode = null;
//        Date randomCodeAddtime = null;
//        try{
//            randomCode = this.getSessionValidCode();;
//            randomCodeAddtime = DateUtils.getDate((long) this.getSession().getAttribute("verifyCodeTime")); ;
//        }catch (NullPointerException e){
//            //未发送短信进行提示
//            Message.RESULT.put("result", "fail");
//            Message.RESULT.put("messageCode", "sysUser.modifyPass.randomCode.no");
//            Message.RESULT.put("message", "请发送短信");
//            return Message.RESULT;
//        }
//
//        Date now = new Date();
//        long between = (now.getTime() - randomCodeAddtime.getTime())/1000;
//
//        if(!(randomCode.equals(mobileCode))){
//            Message.RESULT.put("result", "fail");
//            Message.RESULT.put("messageCode", "sysUser.modifyPass.randomCode.error");
//            Message.RESULT.put("message", "短信验证码输入有误");
//            return Message.RESULT;
//        }
//        if(between > Constants.VALIDATETIME){
//            Message.RESULT.put("result", "fail");
//            Message.RESULT.put("messageCode", "sysUser.modifyPass.randomCode.timeout");
//            Message.RESULT.put("message", "短信验证码已经超时，请重新获取");
//            return Message.RESULT;
//        }
//
//
//        SysTempcode tempcode  = tempcodeService.getByMobileAndCode(user.getMobile(),randomCode);
//
//        try{
//            if(tempcode ==null ){
//                Message.RESULT.put("result", "fail");
//                Message.RESULT.put("messageCode", "sysUser.modifyPass.randomCode.error");
//                Message.RESULT.put("message", "短信验证码输入有误");
//                return Message.RESULT;
//            }
//        }catch(Exception e){
//            Message.RESULT.put("result", "fail");
//            Message.RESULT.put("messageCode", "sysUser.modifyPass.randomCode.error");
//            Message.RESULT.put("message", "短信验证码输入有误");
//            return Message.RESULT;
//        }
//
//        //修改绑定
//        SysUser sysuser = new SysUser();
//        sysuser.setId(sysUserId);
//        sysuser.setUserId(userId);
//        sysUserService.updateNotNull(sysuser);
//
//        this.getSession().removeAttribute("verifyCode");
//        this.getSession().removeAttribute("verifyCodeTime");
//        return Message.OK;
//    }


//    //绑定业务员短信
//    @ResponseBody
//    @RequestMapping(value="/admin/sysUser/bandingSendMessage",method = RequestMethod.POST)
//    public  Object bandingSendMessage(Integer userId){
//        BasUserInfoVo user =userService.getUserInfoById(userId);
//        if (user == null){
//            return Message.FAIL;
//        }
//        if(user.getCustomerType() != 1 && user.getCustomerType() != 2){
//            return Message.FAIL;
//        }
//        SysNoticeType noticeType = noticeTypeService.getNoticeTypeByNid("modifymobile_sms");
//        String content = noticeType.getTypeContent();
//        String  randomCode = RandomCodesUtils.createRandom(true,6);
//        System.out.println("您的验证码：" + randomCode);
//        content = content.replace(Constants.VALIDATECODE, randomCode);
//        String smsResponse=Sms.send("13858101403", content).toString();
//
//        Map ret = new HashMap();
//        if(smsResponse.equals("发送成功")){
//            SysTempcode tempcode= new SysTempcode();
//            tempcode.setCode(randomCode);
//            tempcode.setMobile(user.getMobile());
//            tempcode.setAddtime(new Date());
//            tempcode.setAddip(IpUtils.get());
//            tempcodeService.save(tempcode);
//            this.getSession().setAttribute("verifyCode", randomCode);
//            this.getSession().setAttribute("verifyCodeTime", System.currentTimeMillis());
//            ret.put("result","success");
//            ret.put("validPhoneExpiredTime",new Date());
//        }else {
//            ret.put("result","fail");
//            ret.put("message",smsResponse);
//        }
//        return ret;
//    }


    /**
     * 修改密码
     * newPassword  新密码
     * phoneCode    手机验证码
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/admin/sysuser/modifyPass" ,method = RequestMethod.POST)
    public Object modifyPass(String newPassword,String mobileCode){
        Integer userId=this.getSessionUserId();
        SysUser user = sysUserService.selectByKey(userId);
        if(user ==null){
            Message.RESULT.put("result", "fail");
            Message.RESULT.put("messageCode", "sysUser.modifyPass.user.notExist");
            Message.RESULT.put("message", "不存在该手机用户");
            return Message.RESULT;
        }

        String randomCode = null;
        Date randomCodeAddtime = null;
        try{
            randomCode = this.getSessionValidCode();;
            randomCodeAddtime = DateUtils.getDate((long) this.getSession().getAttribute("verifyCodeTime")); ;
        }catch (NullPointerException e){
            //未发送短信进行提示
            Message.RESULT.put("result", "fail");
            Message.RESULT.put("messageCode", "sysUser.modifyPass.randomCode.no");
            Message.RESULT.put("message", "请发送短信");
            return Message.RESULT;
        }

        Date now = new Date();
        long between = (now.getTime() - randomCodeAddtime.getTime())/1000;

        if(!(randomCode.equals(mobileCode))){
            Message.RESULT.put("result", "fail");
            Message.RESULT.put("messageCode", "sysUser.modifyPass.randomCode.error");
            Message.RESULT.put("message", "短信验证码输入有误");
            return Message.RESULT;
        }
        if(between > Constants.VALIDATETIME){
            Message.RESULT.put("result", "fail");
            Message.RESULT.put("messageCode", "sysUser.modifyPass.randomCode.timeout");
            Message.RESULT.put("message", "短信验证码已经超时，请重新获取");
            return Message.RESULT;
        }


        SysTempcode tempcode  = tempcodeService.getByMobileAndCode(user.getMobile(),randomCode);

        try{
            if(tempcode ==null ){
                Message.RESULT.put("result", "fail");
                Message.RESULT.put("messageCode", "sysUser.modifyPass.randomCode.error");
                Message.RESULT.put("message", "短信验证码输入有误");
                return Message.RESULT;
            }
        }catch(Exception e){
            Message.RESULT.put("result", "fail");
            Message.RESULT.put("messageCode", "sysUser.modifyPass.randomCode.error");
            Message.RESULT.put("message", "短信验证码输入有误");
            return Message.RESULT;
        }

        //修改密码
        try {
            user.setPassword(MD5.toMD5(newPassword+user.getSalt()));
        } catch (UnsupportedEncodingException e) {
            Message.RESULT.put("result", "fail");
            Message.RESULT.put("messageCode", "sysUser.modifyPass.salt.fail");
            Message.RESULT.put("message", "加密失败");
            return Message.RESULT;
        }
        sysUserService.updateNotNull(user);
        this.getSession().removeAttribute("userId");
        this.getSession().removeAttribute("verifyCode");
        this.getSession().removeAttribute("verifyCodeTime");
        return Message.OK;
    }


    //修改手机号码短信
    @ResponseBody
    @RequestMapping(value="/admin/sysUser/modifyMobileSendMessage",method = RequestMethod.POST)
    public  Object modifyMobileSendMessage(){
        Integer userId = this.getSessionUserId();
        SysUser sysUser =sysUserService.selectByKey(userId);
        if (sysUser == null){
            return Message.FAIL;
        }
        SysNoticeType noticeType = noticeTypeService.getNoticeTypeByNid("modifymobile_sms");
        String content = noticeType.getTypeContent();
        String  randomCode = RandomCodesUtils.createRandom(true,6);
        System.out.println("您的验证码：" + randomCode);
        content = content.replace(Constants.VALIDATECODE, randomCode);
        String smsResponse=Sms.send(sysUser.getMobile(), content).toString();

        Map ret = new HashMap();
        if(smsResponse.equals("发送成功")){
            SysTempcode tempcode= new SysTempcode();
            tempcode.setCode(randomCode);
            tempcode.setMobile(sysUser.getMobile());
            tempcode.setAddtime(new Date());
            tempcode.setAddip(IpUtils.get());
            tempcodeService.save(tempcode);
            this.getSession().setAttribute("verifyCode", randomCode);
            this.getSession().setAttribute("verifyCodeTime", System.currentTimeMillis());
            ret.put("result","success");
            ret.put("validPhoneExpiredTime",new Date());
        }else {
            ret.put("result","fail");
            ret.put("message",smsResponse);
        }
       return ret;
    }

//    //企业认证
//    @ResponseBody
//    @RequestMapping(value="/admin/sysUser/guaranteeCertification",method = RequestMethod.POST)
//    public Object guaranteeCertification(BusGuaranteeSecurity security){
//        return sysUserService.guaranteeCertification(security);
//    }


//    //企业信息修改
//    /*
//    * bizType业务类型(默认05-p2p平台用户) 01-投资用户 02-借款用户 03-担保用户 04-咨询用户 05-p2p平台用户 06-借款/投资混合用户
//    * */
//    @ResponseBody
//    @RequestMapping(value="/admin/sysUser/updateEnterprise",method = RequestMethod.POST)
//    public Object updateEnterprise(BusGuaranteeSecurity security,BusAccountBank bank,String bankCardName,String bizType,String newBankCardNo){
//        return sysUserService.updateEnterprise(security, bank,newBankCardNo,bankCardName, bizType);
//    }

    //删除业务员
    @ResponseBody
    @RequestMapping(value="/admin/sysUser/deleteSysUser",method = RequestMethod.POST)
    public  Object deleteSysUser(Integer sysUserId){
        sysUserService.delete(sysUserId);
        return Message.OK;
    }
}
